package com.cda.pes.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * EnableGlobalMethodSecurity : 表示启用方法级别的认证
 * prePostEnabled： boolean：默认为false；
 *                  true：   表示可以使用@PreAuthorize注解和@PostAuthorize
 */
@Configuration  //当前类为配置类
//@EnableWebSecurity //SS启用（默认也是启用的） //控制安全管理内容
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //在方法中配置用户和密码的信息，作为登录的数据
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        PasswordEncoder pe = new MyPasswordEncoder();
        //可以设置内存指定的登录的账号密码,指定角色
        //不加.passwordEncoder(new MyPasswordEncoder())
        //就不是以明文的方式进行匹配，会报错
        auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles();
//        auth.inMemoryAuthentication().withUser("lisi").password("123456").roles();
        auth.inMemoryAuthentication().withUser("admin").password(pe.encode("admin")).roles("admin");
        auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser("wangwu").password("123456").roles("normal");
        //.passwordEncoder(new MyPasswordEncoder())。
        //这样，页面提交时候，密码以明文的方式进行匹配。
        auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser("lisi").password("123456").roles("admin","normal");
    }
//
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
                .antMatchers("/static/**");
    }
//
//    /**
//     * 请求方法
//     * @param http
//     * @throws Exception
//     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        http.httpBasic()    //开启httpbasic认证
//                .and().authorizeRequests().anyRequest().authenticated();    //所有请求都需要认证后访问
        http.formLogin()        //开启表单认证
                .loginPage("/login.html")    //表单提交的路径
                .usernameParameter("username")
                .passwordParameter("password")  //自定义input的值
                .successForwardUrl("/index.html")    //登陆成功后跳转的路径
                .and().authorizeRequests().antMatchers("login.html","index.html").permitAll()   //放行登录页面
                .anyRequest().authenticated();
    }

}
